define(function(require , exports , module){
	
	angular.module("uiSelectree" , [])
	.directive('uiSelectree' , ["$timeout" ,"$compile", "$parse" , function($timeout,$compile , $parse){
		return {
			restrict: 'A',
			require:'ngModel',
			replace: true,
			link:function($scope , $elm , $attrs , ngModel){
					var url = $attrs["url"];
					var id = $attrs["id"];
					var keyField = $attrs.key?attrs.key:"id";
			        var textField = $attrs.text?attrs.text:"name";
					$elm.parent().append(function(){
						return "<input id='ztreeSel' class='"+ id + "ztreeSel' type='text' value='' readonly>"+
								"<span class='select-zTree'><b></b></span>";						
					})	
					
					$elm.parent().append(function(){
						var html = "<div class ='ztreeContent' id='"+id+"ztreeContent' style='display:none;'>" +
									"<ul id ='ztree' ui-ztree  data-url=' " + url + "' filter='" + id + "TreeFilter' click='" + id + "TreeClick'  class='ztree'></ul>"+
									"</div>";
						return $compile(html)($scope);							
					})
					
					$elm.parent().find("span").on("click" , function(){	
						$("#"+id+"ztreeContent").toggle(function(){
							$(this).hide();
						} , function(){
							//$(this).show(); 
							
						});					
					});	
					$elm.parent().find("input").on("click" , function(){	
						$("#"+id+"ztreeContent").toggle(function(){
							$(this).hide();
						} , function(){
							//$(this).show(); 
							
						});					
					});
					
					$scope[id+"TreeClick"] = function(event , treeId , treeNode) {					
						$("."+id+"ztreeSel").val(treeNode.name);
						var getter = $parse($attrs.ngModel);
						getter.assign($scope ,treeNode.id);
						$scope.$apply();
					};
					
					$scope.datas = [];
					$scope[id+"TreeFilter"] = function(data) {
						$scope.datas.push(data);
						var value = $scope.$eval($attrs.ngModel);
						if (value == data.id) {
							$("#ztreeSel").val(data.name);
						}
					};
					
					$scope.$watch($attrs.ngModel , function(newValue , oldValue){
						if ($scope.datas) {
							for (var i = 0,len = $scope.datas.length;i < len;i++) {
								var data = $scope.datas[i];
								if (data.id == newValue) {
									$("#ztreeSel").val(data.name);
								}
							}
							
						}
					});

			}
		};
	}]);
});